import { uploadMinio } from '@/services/common';
import {
  addDocumentInfo,
  deleteDocumentInfo,
  qryDocumentInfoDetail,
  qryDocumentListPage,
  updateDocumentInfo,
} from '@/services/document';
import { PlusOutlined, UploadOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { Button, Form, Input, message, Modal, Popconfirm, Upload } from 'antd';
import React, { useRef, useState } from 'react';

interface DocumentItem {
  fileId: string;
  fileName: string;
  fileType: string;
  fileUrl: string;
  updateTime: string;
  fileSize: string;
}

const DocumentPage: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [form] = Form.useForm();
  const [modalVisible, setModalVisible] = useState(false);
  const [currentDocument, setCurrentDocument] = useState<DocumentItem | null>(
    null,
  );
  const [confirmLoading, setConfirmLoading] = useState(false);

  const handleDelete = async (fileId: string) => {
    try {
      await deleteDocumentInfo({ fileId });
      message.success('删除成功');
      actionRef.current?.reload();
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleEdit = async (fileId: string) => {
    try {
      const detail = await qryDocumentInfoDetail({ fileId });
      setCurrentDocument(detail);
      form.setFieldsValue(detail);
      setModalVisible(true);
    } catch (error) {
      message.error('获取详情失败');
    }
  };

  const columns: ProColumns<DocumentItem>[] = [
    {
      title: '文件ID',
      dataIndex: 'fileId',
      key: 'fileId',
      hideInSearch: true,
      width: 200,
    },
    {
      title: '文件名称',
      dataIndex: 'fileName',
      key: 'fileName',
    },
    {
      title: '文件类型',
      dataIndex: 'fileType',
      hideInSearch: true,
      key: 'fileType',
      width: 120,
    },
    {
      title: '文件大小',
      hideInSearch: true,
      dataIndex: 'fileSize',
      key: 'fileSize',
      width: 120,
    },
    {
      title: '上传时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      hideInSearch: true,
      width: 180,
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      valueType: 'option',
      render: (_, record) => [
        <Button
          key="edit"
          type="link"
          onClick={() => handleEdit(record.fileId)}
        >
          编辑
        </Button>,
        <Popconfirm
          key="delete"
          title="确定要删除这条资料吗?"
          onConfirm={() => handleDelete(record.fileId)}
          okText="确定"
          cancelText="取消"
        >
          <Button type="link" danger>
            删除
          </Button>
        </Popconfirm>,
      ],
    },
  ];

  const handleAdd = () => {
    form.resetFields();
    setCurrentDocument(null);
    setModalVisible(true);
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setConfirmLoading(true);

      if (currentDocument) {
        await updateDocumentInfo({
          ...values,
          fileId: currentDocument.fileId,
        });
        message.success('更新成功');
      } else {
        await addDocumentInfo(values);
        message.success('新增成功');
      }

      setModalVisible(false);
      actionRef.current?.reload();
    } catch (error) {
      message.error('操作失败');
    } finally {
      setConfirmLoading(false);
    }
  };

  const formatFileSize = (bytes: number) => {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  const uploadProps: any = {
    // @ts-ignore
    customRequest: async ({ file, onSuccess, onError }) => {
      try {
        const response = await uploadMinio(file as File);
        if (response.data?.fileUrl) {
          form.setFieldsValue({
            fileName: (file as File).name,
            fileUrl: response.data.fileUrl,
            fileType: (file as File).name.split('.').pop(),
            fileSize: formatFileSize((file as File).size || 0),
          });
          onSuccess?.(response, new XMLHttpRequest());
        } else {
          onError?.(new Error('上传失败'), new XMLHttpRequest());
        }
      } catch (error) {
        onError?.(error as Error, new XMLHttpRequest());
      }
    },
  };

  return (
    <PageContainer>
      <ProTable<DocumentItem>
        actionRef={actionRef}
        rowKey="fileId"
        columns={columns}
        request={async (params) => {
          const { current, pageSize, ...rest } = params;
          console.log(rest);
          const result = await qryDocumentListPage({
            pageIndex: current,
            pageSize,
            param: rest,
          });
          return {
            data: result.list,
            total: result.total,
            success: true,
          };
        }}
        toolBarRender={() => [
          <Button
            key="add"
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleAdd}
          >
            新增资料
          </Button>,
        ]}
      />

      <Modal
        title={currentDocument ? '编辑资料' : '新增资料'}
        open={modalVisible}
        onOk={handleSubmit}
        confirmLoading={confirmLoading}
        onCancel={() => setModalVisible(false)}
        width={800}
      >
        <Form form={form} layout="vertical">
          {currentDocument && (
            <Form.Item name="fileId" label="文件ID" hidden>
              <Input disabled />
            </Form.Item>
          )}
          <Form.Item
            name="fileName"
            label="文件名称"
            rules={[{ required: true, message: '请上传文件' }]}
          >
            <Input placeholder="上传文件后自动填充" disabled />
          </Form.Item>

          <Form.Item
            name="fileUrl"
            label="文件URL"
            rules={[{ required: true, message: '请上传文件' }]}
          >
            <Input disabled />
          </Form.Item>

          <Form.Item label="上传文件">
            <Upload {...uploadProps}>
              <Button icon={<UploadOutlined />}>点击上传文件</Button>
            </Upload>
          </Form.Item>

          <Form.Item name="fileType" label="文件类型">
            <Input disabled />
          </Form.Item>

          <Form.Item name="fileSize" label="文件大小">
            <Input disabled />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default DocumentPage;
